
import { useEffect, useState } from 'react'
import { useMount } from 'ahooks'
import { CSS } from '@dnd-kit/utilities'
import { Input, Button, Result, Radio } from 'antd'
import { v4 } from 'uuid'

import { SortDescendingOutlined, SortAscendingOutlined, CloseCircleOutlined } from '@ant-design/icons'
import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors } from '@dnd-kit/core'
import { useSortable, arrayMove, SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy } from '@dnd-kit/sortable'

import { menuStore } from '../Config/zustand'

const SortableItem = ({ id, label, value, init }) => {
    const { sortConfig, updateSortConfig } = menuStore()

    const [Value, setValue] = useState()
    const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id })
    const style = { transform: CSS.Transform.toString(transform), transition }
    const onClick = () => {
        sortConfig.find(v => v.id === id).init = ''
        setValue('')
        updateSortConfig([...sortConfig])
    }
    const onChange = (e) => {
        sortConfig.find(v => v.id === id).init = e.target.value
        setValue(e.target.value)
        updateSortConfig([...sortConfig])
    }

    const onDelete = () => {
        const data = sortConfig.filter(v => v.id !== id)
        updateSortConfig(data)
    }

    useMount(() => setValue(init))

    return (
        <div className='SortableItem' ref={setNodeRef} style={style} {...attributes}>
            <div {...listeners}> {label} - {value} </div>
            <div>
                <Radio.Group value={Value} onChange={onChange} buttonStyle="solid">
                    <Radio.Button value="asc" ><SortDescendingOutlined /></Radio.Button>
                    <Radio.Button value="desc" ><SortAscendingOutlined /></Radio.Button>
                </Radio.Group>
                <Button type='link' icon={<CloseCircleOutlined />} danger onClick={onClick}>取消默认</Button>
                <Button type='link' icon={<CloseCircleOutlined />} danger onClick={onDelete}>删除字段</Button>
            </div>
        </div>
    )
}

const MenuConfigSort = () => {
    const { sortConfig, updateSortConfig } = menuStore()
    const [sortData, setSortData] = useState([])
    const [labelData, setLabelData] = useState('')
    const [valueData, setValueData] = useState('')

    const onAdded = () => {
        const data = { id: v4(), value: valueData, label: labelData }
        setSortData(e => ([...e, data]))
        sortConfig.push(data)
        updateSortConfig([...sortConfig])
        setLabelData('')
        setValueData('')
    }


    const sensors = useSensors(
        useSensor(PointerSensor),
        useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
    )

    const handleDragEnd = (event) => {
        const { active, over } = event
        if (active.id !== over.id) {
            const oldIndex = sortData.findIndex(v => v.id === active.id)
            const newIndex = sortData.findIndex(v => v.id === over.id)
            const data = arrayMove(sortData, oldIndex, newIndex)
            setSortData(data)
            updateSortConfig(data)
        }
    }

    useEffect(() => setSortData(sortConfig), [sortConfig])

    return (
        <div className='MenuConfigitem MenuConfigSort'>
            <div className='Added'>
                <div className='Title'>新增排序</div>
                <div className='Label' >
                    <div>排序字段</div>
                    <Input value={valueData} onChange={e => setValueData(e.target.value)} />
                </div>
                <div className='Label' >
                    <div>映射名称</div>
                    <Input value={labelData} onChange={e => setLabelData(e.target.value)} />
                </div>
                <div className='AddBtn'>
                    <Button type='primary' block onClick={onAdded}>添加排序字段</Button>
                </div>
            </div>
            <div className='List'>
                {sortData.length === 0 ?
                    <div className='empty'>
                        <Result status="404" title="暂无字段,请现在左侧添加需要排序的字段!" />
                    </div> :
                    <div className='SortBox'>
                        <DndContext handlesensors={sensors} onDragEnd={handleDragEnd} collisionDetection={closestCenter}>
                            <SortableContext items={sortData} strategy={verticalListSortingStrategy}>
                                {sortData.map(({ id, label, value, init }) => <SortableItem key={id} id={id} label={label} value={value} init={init} />)}
                            </SortableContext>
                        </DndContext>
                    </div>
                }
            </div>
        </div>
    );
};

export default MenuConfigSort;